package zkserver

import (
	"core/server/baseserver"
	"core/zookeeper"
	"github.com/dubbogo/gost/log/logger"
	"github.com/go-zookeeper/zk"
)

type LockerServer struct {
	ZkDsn string

	baseserver.BaseServer
	conn *zk.Conn
}

func (p *LockerServer) Start() {
	p.BaseServer.DoInterval = p.DoInterval
	p.BaseServer.DoClose = p.Close

	p.conn, _ = zookeeper.OpenZK(p.ZkDsn)

	p.BaseServer.Start()

}
func (p *LockerServer) Close() {
	if p.conn != nil {
		p.conn.Close()
	}
}
func (p *LockerServer) Lock(path, value string) (bool, error) {

	bexists, _, _, err := p.conn.ExistsW(path)
	if err != nil {
		return false, err
	}
	if bexists {
		bdata, _, err := p.conn.Get(path)
		if err != nil {
			return false, err
		}
		var sdata = string(bdata)
		return sdata == value, nil
	}
	_, err = p.conn.Create(path, []byte(value), zk.FlagEphemeral, zk.WorldACL(zk.PermAll))
	if err != nil {
		logger.Infof("写入错误，请注意 path:%v  错误：%v", path, err)
		return false, err
	}
	return true, nil
}
func (p *LockerServer) UnLock(path, value string) (bool, error) {

	bexists, _, _, err := p.conn.ExistsW(path)
	if err != nil {
		return false, err
	}
	if !bexists {
		return true, err
	}
	bdata, state, err := p.conn.Get(path)
	if err != nil {
		return false, err
	}
	var sdata = string(bdata)
	if sdata != value {
		return true, nil
	}
	err = p.conn.Delete(path, state.Version)
	if err != nil {
		logger.Infof("删除错误，请注意 path:%v  错误：%v", path, err)
		return false, err
	}
	return true, nil
}

func (p *LockerServer) DoInterval() {
	//var path = p.PPath + "/" + p.Path
	//bexists, _, _, err := p.conn.ExistsW(path)
	//if err != nil {
	//	return
	//}
	//if bexists {
	//	return
	//}
	//
	//_, err = p.conn.Create(path, []byte(p.Value), zk.FlagEphemeral, zk.WorldACL(zk.PermAll))
	//if err != nil {
	//	logger.Info("写入错误，请注意")
	//}
}
